package com.winit.openapi.sms;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;

import com.winit.common.query.Page;
import com.winit.common.spi.SPIException;
import com.winit.common.spi.context.CommandContext;
import com.winit.erp.spi.bpartner.BpartnerService;
import com.winit.erp.spi.bpartner.vo.Bpartner;
import com.winit.openapi.constants.ApiConstant;
import com.winit.openapi.constants.ErrorCode;
import com.winit.openapi.controller.BaseController;
import com.winit.openapi.exception.ApiException;
import com.winit.openapi.model.RequestMsg;
import com.winit.openapi.model.ResponseMsg;
import com.winit.openapi.sms.common.SmsUtils;
import com.winit.openapi.util.DateUtil;
import com.winit.sms.spi.common.command.CodeCommand;
import com.winit.sms.spi.common.command.IdCommand;
import com.winit.sms.spi.common.vo.PageVo;
import com.winit.sms.spi.wallet.cashaccount.CashAccountService;
import com.winit.sms.spi.wallet.cashaccount.command.CreateCashAccountCommand;
import com.winit.sms.spi.wallet.cashaccount.command.ModifyCashAccountCommand;
import com.winit.sms.spi.wallet.cashaccount.command.QueryCashAccountLineCommand;
import com.winit.sms.spi.wallet.cashaccount.vo.CashAccountLineVo;
import com.winit.sms.spi.wallet.cashaccount.vo.CashAccountVo;
import com.winit.sms.spi.wallet.creditaccount.command.QueryCreditAccountLineCommand;

/**
 * 现金账户
 * 
 * @version <pre>
 * Author	Version		Date		Changes
 * keke.xu 	1.0  		2016年1月11日 	Created
 * 
 * </pre>
 * @since 1.
 */
@Controller
@RequestMapping("/sms/cashaccount")
public class CashAccountController extends BaseController {

    private static Logger      logger = LoggerFactory.getLogger(CashAccountController.class);
    @Resource
    private CashAccountService cashAccountService;
    @Resource
    private BpartnerService    bpartnerService;

    /**
     * 根据客户编码查询现金账户信息
     * 
     * @param requestMsg
     * @param responseMsg
     * @return
     */
    @RequestMapping("/queryCashAcctByCustomerId")
    public String queryCashAcctByCustomerId(@ModelAttribute RequestMsg requestMsg,
                                            @ModelAttribute ResponseMsg responseMsg) {
        Bpartner bpartner = CommandContext.getContext().get(ApiConstant.API_BPARTNER);
        if (bpartner == null) {
            logger.info(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>bpartner对象为空");
            return ERROR;
        }
        CodeCommand command = new CodeCommand();
        command.setCode(bpartner.getValue());
        CashAccountVo cashAccountVo = cashAccountService.queryCashAcctByCustomerCode(command);
        if(cashAccountVo != null){
        	if (cashAccountVo.getAvailableBalance().compareTo(BigDecimal.ZERO) < 0) {
                cashAccountVo.setOverdraftBalance(cashAccountVo.getAvailableBalance().abs());
            } else {
                cashAccountVo.setOverdraftBalance(BigDecimal.ZERO);
            }
        }
        responseMsg.setData(cashAccountVo);
        return SUCCESS;
    }

    /**
     * 现金账户创建
     * 
     * @param requestMsg
     * @param responseMsg
     * @return
     */
    @RequestMapping("/createCashAcct")
    public String createCashAcct(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {
        Bpartner bpartner = CommandContext.getContext().get(ApiConstant.API_BPARTNER);
        if (bpartner == null) {
            logger.info(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>bpartner对象为空");
            return ERROR;
        }
        CreateCashAccountCommand command = SmsUtils.toJavaObject(requestMsg.getData(), CreateCashAccountCommand.class);
        command.setCustomerCode(bpartner.getValue());
        try {
            cashAccountService.createCashAcct(command);
        } catch (Exception e) {
            throw new ApiException(ErrorCode.SYSTEM_ERROR);
        }
        return SUCCESS;
    }

    /**
     * 查询现金账户信息
     * 
     * @param requestMsg
     * @param responseMsg
     * @return
     */
    @RequestMapping("/queryCashAcct")
    public String queryCashAcct(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {
        IdCommand command = SmsUtils.toJavaObject(requestMsg.getData(), IdCommand.class);
        try {
            logger.info(">>>>>>>>>>>>>>>>>>>>>>>>queryCashAcct:" + command.toString());
            CashAccountVo cashAccountVo = cashAccountService.queryCashAcct(command);
            responseMsg.setData(cashAccountVo);
        } catch (Exception e) {
            throw new ApiException(ErrorCode.SYSTEM_ERROR);
        }
        return SUCCESS;
    }

    /**
     * 修改现金账户
     * 
     * @param requestMsg
     * @param responseMsg
     * @return
     */
    @RequestMapping("/modifyCashAcct")
    public String modifyCashAcct(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {
        ModifyCashAccountCommand command = SmsUtils.toJavaObject(requestMsg.getData(), ModifyCashAccountCommand.class);
        Bpartner bpartner = CommandContext.getContext().get(ApiConstant.API_BPARTNER);
        if (bpartner == null) {
            logger.info(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>bpartner对象为空");
            return ERROR;
        }
        command.setCustomerCode(bpartner.getValue());
        try {
            cashAccountService.modifyCashAcct(command);
        } catch (Exception e) {
            throw new ApiException(ErrorCode.SYSTEM_ERROR);
        }
        return SUCCESS;
    }

    /**
     * 现金账户交易明细分页查询
     * 
     * @param requestMsg
     * @param responseMsg
     * @return
     */
    @RequestMapping("/pageCashAcct")
    public String pageCashAcct(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {
        QueryCashAccountLineCommand command = SmsUtils.toJavaObject(requestMsg.getData(),
            QueryCashAccountLineCommand.class);
        if (command == null) {
        	logger.info(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>pageCashAcct command对象为空");
            return ERROR;
        }
        if (null != command.getTransactionDateEnd()) {
            command.setTransactionDateEnd(DateUtil.spliceDate(command.getTransactionDateEnd()));
        }
        logger.info(">>>>>>>>>>>>>>>>>>>>>>>>pageCashAcct:" + command.toString());
        Bpartner bpartner = CommandContext.getContext().get(ApiConstant.API_BPARTNER);
        if (bpartner == null) {
            logger.info(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>bpartner对象为空");
            return ERROR;
        }
        command.setCustomerCode(bpartner.getValue());
        PageVo pageVo = SmsUtils.SetPageParams(requestMsg.getData());
        command.setPageVo(pageVo);
        try {
            Page<CashAccountLineVo> pageCashAcct = cashAccountService.pageCashAcct(command);

            Map<String, Object> data = SmsUtils.setPageData(pageCashAcct);
            data = buildSumAmount(data, command);
            
            CashAccountVo cashAccountVo = cashAccountService.queryTransferAmount(command);
            if(cashAccountVo == null){
            	cashAccountVo = new CashAccountVo();
            }
            data.put("cashAccountVo", cashAccountVo);
            responseMsg.setData(data);
        } catch (Exception e) {
            throw new ApiException(ErrorCode.SYSTEM_ERROR);
        }
        return SUCCESS;
    }

    private Map<String, Object> buildSumAmount(Map<String, Object> data, QueryCashAccountLineCommand command) {
        if (null == data) {
            data = new HashMap<String, Object>();
        }
        CashAccountLineVo cashAcctVo = cashAccountService.querySumAmount(command);
        if (null == cashAcctVo) {
            data.put("SumSourceAmount", BigDecimal.ZERO);
            data.put("SumStandardAmount", BigDecimal.ZERO);
            return data;
        }
        if (null == cashAcctVo.getSourceAmount()) {
            data.put("SumSourceAmount", BigDecimal.ZERO);
        } else {
            data.put("SumSourceAmount", cashAcctVo.getSourceAmount());
        }
        if (null == cashAcctVo.getStandardAmount()) {
            data.put("SumStandardAmount", BigDecimal.ZERO);
        } else {
            data.put("SumStandardAmount", cashAcctVo.getStandardAmount());
        }
        return data;
    }

    /**
     * 导出现金账户交易明细
     * 
     * @param command
     * @return
     */
    @RequestMapping("/exportCashAcctLine")
    public String exportCashAcctLine(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {
        QueryCashAccountLineCommand command = SmsUtils.toJavaObject(requestMsg.getData(),
            QueryCashAccountLineCommand.class);
        if (null != command.getTransactionDateEnd()) {
            command.setTransactionDateEnd(DateUtil.spliceDate(command.getTransactionDateEnd()));
        }
        logger.info(">>>>>>>>>>>>>>>>>>>>>>>>exportCashAcctLine:" + command.toString());
        Bpartner bpartner = CommandContext.getContext().get(ApiConstant.API_BPARTNER);
        if (bpartner == null) {
            logger.info(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>bpartner对象为空");
            return ERROR;
        }
        command.setCustomerCode(bpartner.getValue());
        String path = null;
        try {
            path = cashAccountService.exportCashAcctLine(command);
            logger.info("现金账户交易明细导出路径：{}", path);
        } catch (SPIException e) {
            logger.error(e.getMessage());
            responseMsg.setCode(e.getErrorCode());
            responseMsg.setMsg(e.getErrorMsg());
            return ERROR;
        }
        responseMsg.setData(path);
        return SUCCESS;
    }

    /**
     * 客户冻结现金账户交易明细
     * 
     * @param requestMsg
     * @param responseMsg
     * @return
     */
    @RequestMapping("/pageCashAcctLine")
    public String pageCashAcctLine(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {
        QueryCashAccountLineCommand command = SmsUtils.toJavaObject(requestMsg.getData(),
            QueryCashAccountLineCommand.class);
        if (null != command.getTransactionDateEnd()) {
            command.setTransactionDateEnd(DateUtil.spliceDate(command.getTransactionDateEnd()));
        }
        logger.info(">>>>>>>>>>>>>>>>>>>>>>>>pageCashAcct:" + command.toString());
        Bpartner bpartner = CommandContext.getContext().get(ApiConstant.API_BPARTNER);
        if (bpartner == null) {
            logger.info(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>bpartner对象为空");
            return ERROR;
        }
        command.setCustomerCode(bpartner.getValue());
        PageVo pageVo = SmsUtils.SetPageParams(requestMsg.getData());
        command.setPageVo(pageVo);
        try {
            Page<CashAccountLineVo> pageCashAcct = cashAccountService.pageCashAcctLineByCustomerCode(command);
            if (pageCashAcct == null) {
                return SUCCESS;
            }
            Map<String, Object> data = SmsUtils.setPageData(pageCashAcct);

            CashAccountLineVo vo = cashAccountService.queryCashAcctLineSum(command);

            if (vo == null) {
                return SUCCESS;
            }

            if (null == data) {
                data = new HashMap<String, Object>();
            }

            data.put("SumSourceAmount", vo.getSourceAmount() == null ? BigDecimal.ZERO : vo.getSourceAmount());
            data.put("SumStandardAmount", vo.getStandardAmount() == null ? BigDecimal.ZERO : vo.getStandardAmount());

            responseMsg.setData(data);
        } catch (Exception e) {
            throw new ApiException(ErrorCode.SYSTEM_ERROR);
        }
        return SUCCESS;
    }

    /**
     * 现金未解冻交易明细导出
     * 
     * @param requestMsg
     * @param responseMsg
     * @return
     */
    @RequestMapping("/exportCashAcct")
    public String exportCashAcct(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {
        QueryCreditAccountLineCommand command = SmsUtils.toJavaObject(requestMsg.getData(),
            QueryCreditAccountLineCommand.class);
        Bpartner bpartner = CommandContext.getContext().get(ApiConstant.API_BPARTNER);
        if (bpartner == null) {
            logger.info(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>bpartner对象为空");
            return ERROR;
        }
        command.setCustomerCode(bpartner.getValue());
        if (null != command.getTransactionDateEnd()) {
            command.setTransactionDateEnd(DateUtil.spliceDate(command.getTransactionDateEnd()));
        }
        String path = null;
        try {
            path = cashAccountService.exportCashAcct(command);
            logger.info("信用交易明细导出路径：{}", path);
        } catch (SPIException e) {
            logger.error(e.getMessage());
            responseMsg.setCode(e.getErrorCode());
            responseMsg.setMsg(e.getErrorMsg());
            responseMsg.setData(com.winit.sms.spi.common.constant.Constants.UPLOAD_FA);
            return ERROR;
        }
        responseMsg.setData(path);
        return SUCCESS;
    }

}
